<template>
    <div class="map-wrap">
        <div class="search-map">
            <Input v-model="form.address" element-id="searchAddress" search placeholder="输入地址查询" style="width: 480px;" />
        </div>
        <div id="allmap" class="allmap"></div>
    </div>
</template>

<script>
// import BMap from 'BMap';
export default {
    name: 'BMap',
    props: {
        show: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            ac: null,
            mapExam: undefined, // 地图实例
            locationStr: '',
            form: {
                lng: null,
                lat: null,
                address: ''
            }
        };
    },
    mounted() {
        // 实例化地图
        const map = new BMap.Map('allmap'); // 创建地图实例
        map.centerAndZoom(new BMap.Point(106.55843416, 29.56899625), 13); // 初始化地图，设置中心点坐标和地图级别
        map.enableScrollWheelZoom(); //启用滚轮放大缩小，默认禁用
        map.enableContinuousZoom(); //启用地图惯性拖拽，默认禁用

        // 地图点击事件
        map.addEventListener('click', e => {
            // 清除已有覆盖物
            map.clearOverlays();
            // 添加覆盖物
            map.addOverlay(new BMap.Marker(e.point));
            // 设置中心点
            // map.panTo(e.point);
            // 逆地址解析
            this.geocAddress(e.point);
        });

        // 创建自动完成
        const ac = new BMap.Autocomplete({
            input: 'searchAddress',
            location: map
        });
        // 鼠标点击下拉列表后的事件
        ac.addEventListener('onconfirm', e => {
            map.clearOverlays(); // 移除地图上的标注
            var local = new BMap.LocalSearch(map, {
                renderOptions: {
                    selectFirstResult: false,
                    autoViewport: true
                },
                //智能搜索
                onSearchComplete: results => {
                    let poi = results.getPoi(0); //获取第一个智能搜索的结果
                    var searchpt = poi.point; // 获取坐标
                    map.centerAndZoom(searchpt, 17);
                    map.addOverlay(new BMap.Marker(searchpt)); //添加标注
                    this.form.lat = searchpt.lat;
                    this.form.lng = searchpt.lng;
                    // this.geocAddress(searchpt); // 逆地址解析
                }
            });
            // 搜索词
            var searchValue = e.item.value;
            this.form.address = searchValue.business;
            ac.setInputValue(searchValue.business);
            local.search(searchValue.province + searchValue.city + searchValue.district + searchValue.street + searchValue.business);
        });
        
        this.ac = ac;
        this.mapExam = map;
    },
    watch: {
        show(newval) {
            if(newval) {
                this.handlePanCenter();
            }
        }
    },
    methods: {
        // 初始定位
        init() {
            const that = this;
            let map = this.mapExam;
            // 直接定位城市
            let myCity = new BMap.LocalCity();
            myCity.get(function(result) {
                map.addOverlay(new BMap.Marker(result.center));
                map.setCenter(result.name);
                map.setCurrentCity(result.name);
            });
            // 浏览器定位
            let geolocation = new BMap.Geolocation();
            geolocation.getCurrentPosition(
                function(r) {
                    if(that.form.lat) return false;
                    if (this.getStatus() === BMAP_STATUS_SUCCESS) {
                        if (r.point.lng !== 0 && r.point.lat !== 0) {
                            map.centerAndZoom(r.point, 16);
                        }
                    }
                },
                {
                    enableHighAccuracy: true
                }
            );
        },
        // 设置定位
        setLocation({lng, lat, title}) {
            this.form.lng = lng;
            this.form.lat = lat;
            this.form.address = title;
            this.$nextTick(() => {
                let point = new BMap.Point(lng, lat);
                this.mapExam.clearOverlays();
                this.mapExam.addOverlay(new BMap.Marker(point));
                this.mapExam.centerAndZoom(point, 16); // 初始化地图，设置中心点坐标和地图级别
                this.ac.setInputValue(title);
            })
        },
        // 移动至中心
        handlePanCenter() {
            const { lng, lat } = this.form;
            if(!lng || !lat) return false;
            setTimeout(() => {
                this.mapExam.panTo(new BMap.Point(lng, lat));
            }, 100)
        },
        // 逆地址解析
        geocAddress(point) {
            var geoc = new BMap.Geocoder();
            geoc.getLocation(point, (geocInfo) => {
                // console.log(geocInfo)
                let addr = {
                    lng: point.lng,
                    lat: point.lat,
                    address: geocInfo.addressComponents.street + geocInfo.addressComponents.streetNumber
                }
                if (geocInfo.surroundingPois.length > 0) {
                    addr.address = addr.address + geocInfo.surroundingPois[0].title;
                }
                this.form = addr;
                this.$emit('on-change', addr);
            });
        },
        // 根据地址信息定位
        handleGetTheLocation() {
            if (this.locationStr) {
                this.mapExam.clearOverlays();
                this.mapExam.centerAndZoom(this.locationStr, 18);
                var local = new BMap.LocalSearch(this.mapExam, {
                    renderOptions: {
                        map: this.mapExam
                    }
                });
                local.search(this.locationStr);
            }
        },
        getAddress() {
            return this.form;
        },
        getCenter() {
            return this.mapExam.getCenter();
        }
    },
    destroy() {
        if (this.mapExam) {
            this.mapExam = null;
        }
    }
};
</script>

<style>
.map-wrap {
    height: 100%;
}
.search-map {
    margin-bottom: 20px;
}
.map-group {
    width: 100%;
    height: 560px;
    overflow: hidden;
}
.allmap {
    height: calc(100% - 52px);
    min-height: 400px;
}
.tangram-suggestion-main {
    z-index: 9999 !important;
}
</style>
